/**
 * @(#) ReqVacationMediator.as
 *
 * @date		2009. 03. 06.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	근무 - Mediator
 * 				근무관리 Presentation Logic을 관리 
 */
package com.skt.common_hr.work_nos.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.approval.RequestApprovalMediator;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.work_nos.WorkFacade;
	import com.skt.common_hr.work_nos.model.CalendarProxy;
	import com.skt.common_hr.work_nos.model.ReqVacationProxy;
	import com.skt.common_hr.work_nos.model.VacationApprovalProxy;
	import com.skt.common_hr.work_nos.model.VacationCodeProxy;
	import com.skt.common_hr.work_nos.model.VacationQuotaProxy;
	import com.skt.common_hr.work_nos.model.vo.DateVO;
	import com.skt.common_hr.work_nos.model.vo.ReqVacationVO;
	import com.skt.common_hr.work_nos.view.components.ReqVacationView;
	import com.wcl.utils.StringUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	
	public class ReqVacationMediator extends CommonMediator
	{
		public static const NAME:String = "ReqVacationMediator"; 

		public var baseDate:Date;	
		private var _currentKey:String;
		private var _savingTable:Array;

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function ReqVacationMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
		override protected function initializeView():void
 		{
 			setEventListener();
 			// 휴가사용일수를 가져오고
 			var quotaProxy:VacationQuotaProxy = facade.retrieveProxy(VacationQuotaProxy.NAME) as VacationQuotaProxy;
			view.quotaList = quotaProxy.quotaList;
			
			// 휴가 코드리스트를 가져온다.
 			var codeProxy:VacationCodeProxy = facade.retrieveProxy(VacationCodeProxy.NAME) as VacationCodeProxy;
			view.vacationCodeList = codeProxy.vacationList;
			
			//휴가 추가 - 20111214
			var calendarProxy:CalendarProxy = facade.retrieveProxy(CalendarProxy.NAME) as CalendarProxy;
			//view.bHoliVacation = calendarProxy.bHoliVacation;
			setHolidayList(calendarProxy.holidayList);
			

 		}
		
		private function setEventListener():void
		{
 			// 각 버튼들의 Event Handler를 설정하고
 			view.addEventListener(ReqVacationView.CONFIRM, onConfirm);
 			view.addEventListener(ReqVacationView.CANCEL, onCancel);
 			view.addEventListener(ReqVacationView.ADD_RECORD, onClickAddRecord);
 			view.addEventListener(ReqVacationView.DEL_RECORD, onDelRecord);
		} 		
 		
 		//20111214
		private function setHolidayList(voList:ArrayCollection):void
		{
			var arr:Array = new Array();
			for each(var tmp:DateVO in voList)
			{
				arr.push(tmp.DATUM);
			}
			view.holidays = arr;
		}
		 		
 		public function exec(date:Date):void
 		{
 			bActivated = true;
 			baseDate = new Date(date);
			// 입력레코드를 생성한다.
 			var reqList:ArrayCollection = new ArrayCollection();
 			view.reqList = new ArrayCollection();
 			addRecord();
 		}
 		
		private function closeView(cancel:Boolean=false):void
		{
			bActivated = false;
			PopUpManager.removePopUp(view);
			facade.sendNotification((cancel) ? WorkFacade.CANCEL_REQ_WORKTIME:WorkFacade.SUCCEED_REQ_WORKTIME, this);
		}
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					WorkFacade.INSERT_REQ_VACATION_COMPLETE,
					WorkFacade.INSERT_REQ_VACATION_FAILED,
					RequestApprovalMediator.APPROVAL_CANCEL,
					RequestApprovalMediator.APPROVAL_COMPLETE
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			if(bActivated) {
				switch(note.getName()) 
				{
					case WorkFacade.INSERT_REQ_VACATION_COMPLETE:
						_currentKey = ReqVacationProxy(note.getBody()).outKey; 
						execApproval(_currentKey);
						break;
					case WorkFacade.INSERT_REQ_VACATION_FAILED:
						CommonAlert.showMessage( commonFacade.bundle, "("+note.getBody().retCode+")"+note.getBody().retText, null, "RFC 오류", view);
						break;
					case RequestApprovalMediator.APPROVAL_COMPLETE:					// 결재 요청  성공
						closeView();
						break;
					case RequestApprovalMediator.APPROVAL_CANCEL:					// 결재 요청 취소
						cancelApproval(_currentKey);
						facade.sendNotification(WorkFacade.CANCEL_REQ_WORKTIME, this);
						break;
					default:
						//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
						break;
				}
			}
		}


 		private function onConfirm(event:Event):void
 		{
 			var table:Array = new Array();
 			var i:int = 0;
 			for each(var src:ReqVacationVO in view.reqList)
 			{
 				if(src.selectedIndex<=0) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_VACATIONTYPE");
 					return;
 				}
 				if(Number(src.BEGDA) > Number(src.ENDDA)) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_VACATIONTIME");
 					return;
 				}
 				/* /* 20141101 최부장님요청
 				if(!checkHoliday(src.BEGDA)) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_VACATION_DATE");
 					return;
 				}
 				*/ 
 				if(StringUtil.NVL(src.TEXT1) == "") { 
 					CommonAlert.showMessage(commonFacade.bundle, "휴가 신청 사유를 반드시 입력하여 주십시오.");
 					return;
 				} 
 				src.SEQNO = (i++).toString(); 
 				src.PERNR = src.IPERNR = Variables.myPernr;
 				src.DGBN  = "1";
 				src.BEGUZ = null;
 				src.ENDUZ = null;
 				src.AWART = view.vacationCodeList.getItemAt(src.selectedIndex).code;
 				src.AWATX = view.vacationCodeList.getItemAt(src.selectedIndex).text;
//shgoo : 대휴(반일) 항목 처리 추가  2009.05.22 		ReqVacationView.CONFIRM		
// 				if(src.AWART=="0120") // 반차
 				if(src.AWART == ReqVacationView.HALF_VACATION || src.AWART == ReqVacationView.HALF_VACATION_DEPT) // 반차, 대휴(반일)
///////////////////
 				{
 					src.APM = (src.bAM) ? "A" : "P";
 					src.ENDDA = src.BEGDA;
 					src.BEGUZ = new Date(src.BEGDA);
 					src.BEGUZ.hours = (src.bAM) ? 9 : 13;
 				}
 				table.push(src);
 			}
 			saveVacation(table);
 			//proxy.InsertVacation("2", table);
 			//PopUpManager.removePopUp(view);
 		}
 		
 		private function saveVacation(table:Array):void
 		{
			var proxy:ReqVacationProxy = facade.retrieveProxy(ReqVacationProxy.NAME) as ReqVacationProxy;
  			_savingTable = table;
  			_savingTable.sort();
			proxy.InsertVacation("2", table);
 		}
 		


		private function checkHoliday(target:Date):Boolean
 		{
 			if(target.day==0 || target.day==6) {
 				return false;
 			}
			return  true;
 		}
 		
 		private function onCancel(event:Event):void
 		{
 			closeView();
 		}
 		
 		private function onClickAddRecord(event:Event):void
 		{
 			addRecord();
 		}
 		
 		
 		private function addRecord():void
 		{
 			var vo:ReqVacationVO = new ReqVacationVO();
 			vo.selectedIndex = 0;
 			vo.BEGDA = new Date(baseDate);
 			vo.ENDDA = new Date(baseDate);
 			view.reqList.addItem(vo);
 		}
 		
 		private function onDelRecord(event:Event):void
 		{
			for (var i:int=0; i<view.reqList.length; i++)
			{
				if(view.reqList.getItemAt(i).del) {
					view.reqList.removeItemAt(i--);
				}
			} 			
			if(view.reqList.length==0) {
				addRecord();
			}
 		}

 		private function execApproval(key:String):void
 		{
 			var approval:RequestApprovalMediator = facade.retrieveMediator(RequestApprovalMediator.NAME) as RequestApprovalMediator;
 			if(approval==null) {
 				approval = new RequestApprovalMediator(view, "01");
 				facade.registerMediator(approval);
 			}
 			
 			var appProxy:VacationApprovalProxy = facade.retrieveProxy(VacationApprovalProxy.NAME) as VacationApprovalProxy;
 			appProxy.key = key;
 			appProxy.dataProvider = _savingTable;
 			approval.execRequest(view, appProxy);
 		}

 		private function cancelApproval(key:String):void
 		{
 			var proxy:ReqVacationProxy = facade.retrieveProxy(ReqVacationProxy.NAME) as ReqVacationProxy;
 			proxy.del([{GWAREKEY: key}]);
 		}
 		

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ReqVacationView
        {
            return viewComponent as ReqVacationView;
        }
	}
}